<template>
  <div class="tags-container">
    <el-card>
      <!-- 面包屑 -->
      <div v-if="subjects.id && subjects.name">
        <el-breadcrumb separator-class="el-icon-arrow-right" separator="/subjects">
          <el-breadcrumb-item :to='{ path: "list" }'>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            subjects.id ? subjects.name : ''
          }}</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-divider></el-divider>
      </div>
      <!-- 搜索 -->
      <el-row>
        <el-form :inline="true" size="small">
          <el-col :span="18">
            <el-form-item label="标签名称" label-width="80px" v-model="label">
              <el-input v-model.trim="tagName" placeholder="请输入标签名称"></el-input>
            </el-form-item>
            <el-form-item label="状态" label-width="80px" prop="state">
              <el-select placeholder="请选择" v-model="state">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button size="small" @click="reste">清除</el-button>
              <el-button type="primary" size="small" @click="search"
                >搜索</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-form-item>
              <el-button
                style="font-size: 14px"
                type="text"
                v-if="subjects.id && subjects.name"
                @click="$router.push('/subjects/list')"
                icon="el-icon-back"
                >返回学科</el-button
              >
              <el-button
                type="success"
                @click="biulick"
                size="small"
                icon="el-icon-edit"
                >新增标签</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <!-- 数据条数 -->
      <el-alert
        style="margin-bottom: 15px"
        :title="counts"
        type="info"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 表格 -->
      <el-table  v-loading="loading" :data="list" style="width: 100%" :header-cell-style="headClass">
        <el-table-column
          type="index"
          :index="indexMethod"
          label="序号"
          width="80"
        >
        </el-table-column>
        <el-table-column prop="subjectName" width="212" label="所属学科">
        </el-table-column>
        <el-table-column prop="tagName" label="标签名称"> </el-table-column>
        <el-table-column prop="username" label="创建者"></el-table-column>
        <el-table-column
          prop="addDate"
          :formatter="dateFormat"
          label="创建日期"
        ></el-table-column>
        <el-table-column
          prop="state"
          :formatter="formatEmployment"
          label="状态"
        ></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <div class="cell">
              <el-button @click="upOff(row)" type="text">{{
                row.state === 0 ? '启用' : '禁用'
              }}</el-button>
              <el-button
                :disabled="row.state === 0"
                @click="edit(row)"
                type="text"
                >修改</el-button
              >
              <el-button
                @click="del(row.id)"
                type="text"
                :disabled="row.state === 0"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div
        style="
          margin-top: 20px;
          text-align: right;
          margin-left: -20px !important;
        "
      >
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagesize"
          background
          layout=" prev, pager, next, sizes,jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 新增标签的弹层 -->
      <el-dialog
        :visible="showDialog"
        destroy-on-close
        width="400px"
        :title="showTitle"
        :before-close="handleClose"
        @closed="cnm"
      >
        <!-- 表单内容 -->
        <el-form ref="addForm" label-width="80px" :model="form"
        :rules="rules">
          <el-form-item
            label="所属学科"
            v-if="!subjects.id && !subjects.name"
            prop="subjectID"
          >
            <el-select
              style="width: 100%"
              placeholder="请选择"
              v-model="form.subjectID"
            >
              <!-- el-option: label给用户看 value提交后端 -->
              <el-option
                v-for="item in addList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称" prop="tagName">
            <el-input
              v-model.trim="form.tagName"
              style="width: 100%"
              placeholder="请输入标签名称"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="text-align: right">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { list, add, changeState, remove, update } from '../../api/hmmm/tags'
import { simple } from '../../api/hmmm/subjects'
import moment from 'moment'
export default {
  name: 'tags',
  data () {
    return {
      pageList: [],
      label: '',
      list: [],
      page: 1,
      pagesize: 5,
      subjectID: '',
      tagName: '',
      state: null,
      total: 0,
      counts: '',
      showDialog: false,
      subject: {},
      show: false,
      form: {
        subjectID: '',
        tagName: ''
      },
      obj: {
        id: '',
        state: ''
      },
      addList: [],
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur'] }
        ],
        tagName: [
          {
            required: true,
            message: '请输入标签名称',
            trigger: ['blur', 'change']
          }
        ]
      },
      loading: false
    }
  },
  created () {
    this.getList()
    this.submit()
  },
  computed: {
    showTitle () {
      // 新增 form没id 编辑中有id
      return this.form.id ? '修改标签' : '新增标签'
    },
    subjects () {
      return this.$route.query || null
    }
  },
  watch: {
    '$route.query' () {
      this.getList()
    }

  },

  methods: {
    async submit () {
      const { data } = await simple()
      this.addList = data
      this.form.subjectID = +this.addList.value
    },
    headClass () {
      return 'background:#fafafa'
    },
    // 表单获取
    async getList (tagName, state) {
      this.loading = true
      const obj = { page: this.page, pagesize: this.pagesize }
      if (tagName || state) {
        this.page = 1
        obj.tagName = tagName
        obj.state = state
      }
      if (this.subjects.id && this.subjects.name) {
        obj.subjectID = this.subjects.id
      }
      const { data } = await list(obj)
      this.total = data.counts
      this.counts = '数据一共有' + this.total + '条'
      this.list = data.items
      this.form.subjectID = this.subjects.id || null
      this.loading = false
    },
    indexMethod (index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 设置状态
    formatEmployment (row, column, cellValue, index) {
      const status = [
        {
          value: 1,
          label: '已启用'
        },
        {
          value: 0,
          label: '已禁用'
        }
      ]
      const res = status.find((item) => item.value === +cellValue)
      return res ? res.label : '未知'
    },
    // 每页显示条数改变时
    handleSizeChange (newSize) {
      this.pagesize = newSize
      this.page = 1
      if (this.show) return this.getList(this.tagName, this.state)
      this.getList()
    },
    // 页码值改变时
    handleCurrentChange (newPage) {
      this.page = newPage
      // this.search()
      if (this.show) return this.getList(this.tagName, this.state)
      this.getList()
    },
    handleClose () {
      this.showDialog = false
    },
    cnm () {
      this.$refs.addForm.resetFields()
      this.form = {
        subjectID: '',
        tagName: ''
      }
    },
    // 转换时间
    dateFormat (row, column) {
      const date = row[column.property]
      if (date === undefined) return ''
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 搜索功能
    search () {
      this.show = true
      this.page = 1
      this.getList(this.tagName, this.state)
    },
    // 新增和修改
    handleSubmit () {
      this.tagName = ''
      this.state = null
      // 兜底校验
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return
        // 判断是哪个业务逻辑
        const obj = {}
        if (!this.form.id) {
          obj.tagName = this.form.tagName
          if (this.subjects.id) {
            obj.subjectID = +this.subjects.id
          } else {
            obj.subjectID = +this.form.subjectID
          }
          // 发请求
          const { data: res } = await add(obj)
          // 判断结果提醒用户
          if (res.id === 0) return this.$message.error('添加失败')
          this.$message.success('添加标签成功')
        } else {
          await update(this.form)
          this.$message.success('修改标签成功')
        }
        this.getList()
        this.showDialog = false
      })
    },
    // 启用、禁用
    async upOff (val) {
      if (val.state === 1) {
        val.state = 0
      } else {
        val.state = 1
      }
      this.obj.id = val.id
      this.obj.state = val.state

      await changeState(this.obj)
      this.$message.success('操作成功')
      this.getList(this.tagName, this.state)
    },
    // 删除标签
    del (id) {
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', { type: 'warning' }).then(async () => {
        await remove({ id })
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除标签成功')
        this.getList(this.tagName, this.state)
      })
    },
    // 修改标签
    async edit (val) {
      this.showDialog = true
      this.form = { ...val }
    },
    // 清空表单
    reste () {
      this.state = ''
      this.tagName = ''
      this.show = false
    },
    biulick () {
      this.showDialog = true
      if (!(this.subjects.id && this.subjects.name)) this.form.subjectID = ''
    }
  }
}
</script>

<style scoped lang="scss">
.tags-container {
  background: #f0f2f5;
  padding: 10px;
}
::v-deep .el-breadcrumb__inner {
  color: #000;
}
</style>
